<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>python面试题(不定期更新) | Miki&#39;s blog</title>
  <meta name="keywords" content=" python ">
  <meta name="description" content="python面试题(不定期更新) | Miki&#39;s blog">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="keywords: author: Miki language: zh-CN timezone:">
<meta property="og:type" content="website">
<meta property="og:title" content="标签">
<meta property="og:url" content="http://mikiblog.online/tags/index.html">
<meta property="og:site_name" content="Miki&#39;s blog">
<meta property="og:description" content="keywords: author: Miki language: zh-CN timezone:">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-02-22T01:48:02.000Z">
<meta property="article:modified_time" content="2020-02-22T01:50:40.651Z">
<meta property="article:author" content="Miki Zhu">
<meta name="twitter:card" content="summary">


<link rel="icon" href="/img/1.jpg">

<link href="/css/style.css?v=1.0.1" rel="stylesheet">

<link href="/css/hl_theme/atom-dark.css?v=1.0.1" rel="stylesheet">

<link href="//cdn.bootcss.com/animate.css/3.5.2/animate.min.css" rel="stylesheet">
<link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="/js/jquery.autocomplete.min.js?v=1.0.1" ></script>

<script src="//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
<script>
    hljs.initHighlightingOnLoad();
</script>

<script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>



<script src="/js/iconfont.js?v=1.0.1" ></script>

<meta name="generator" content="Hexo 4.2.0"></head>
<div style="display: none">
  <input class="theme_disqus_on" value="false">
  <input class="theme_preload_comment" value="false">
  <input class="theme_blog_path" value="">
</div>

<body>
<aside class="nav">
    <div class="nav-left">
        <a href="/" class="avatar_target">
    <img class="avatar" src="/img/头像.jpg" />
</a>
<div class="author">
    <span>Miki Zhu</span>
</div>

<div class="icon">
    
        
    
        
        <a title="email" href="mailto:747876457@qq.com" target="_blank">
            
                <svg class="iconfont-svg" aria-hidden="true">
                    <use xlink:href="#icon-email"></use>
                </svg>
            
        </a>
        
    
        
        <a title="qq" href="http://wpa.qq.com/msgrd?v=3&uin=747876457&site=qq&menu=yes" target="_blank">
            
                <svg class="iconfont-svg" aria-hidden="true">
                    <use xlink:href="#icon-qq"></use>
                </svg>
            
        </a>
        
    
</div>




<ul>
    <li><div class="all active">全部文章<small>(29)</small></div></li>
    
        
            
            <li><div data-rel="机器学习">机器学习<small>(7)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="机器学习实战">机器学习实战<small>(3)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="项目实战">项目实战<small>(4)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="博客搭建">博客搭建<small>(2)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="算法">算法<small>(3)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="python教程">python教程<small>(1)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="学习网站推荐">学习网站推荐<small>(1)</small></div>
                
            </li>
            
        
    
        
            
            <li><div data-rel="考研经验">考研经验<small>(1)</small></div>
                
            </li>
            
        
    
</ul>
<div class="left-bottom">
    <div class="menus">
    
    
    
    
    </div>
    <div><a class="about  " target="_blank" href="/about">关于</a></div>
</div>
<input type="hidden" id="yelog_site_posts_number" value="29">
<input type="hidden" id="yelog_site_word_count" value="62.1k">
<div style="display: none">
    <span id="busuanzi_value_site_uv"></span>
    <span id="busuanzi_value_site_pv"></span>
</div>

    </div>
    <div class="nav-right">
        <div class="friends-area">
    <div class="friends-title">
        友情链接
        <i class="back-title-list"></i>
    </div>
    <div class="friends-content">
        <ul>
            
        </ul>
    </div>
</div>
        <div class="title-list">
    <form onkeydown="if(event.keyCode === 13){return false;}">
        <input id="local-search-input" class="search" type="text" placeholder="Search..." />
        <i class="cross"></i>
        <span>
            <label for="tagswitch">Tags:</label>
            <input id="tagswitch" type="checkbox" style="display: none" />
            <i id="tagsWitchIcon"></i>
        </span>
    </form>
    <div class="tags-list">
    
    <li class="article-tag-list-item">
        <a class="color5">机器学习</a>
    </li>
    
    <li class="article-tag-list-item">
        <a class="color3">算法</a>
    </li>
    
    <li class="article-tag-list-item">
        <a class="color5">博客搭建</a>
    </li>
    
    <li class="article-tag-list-item">
        <a class="color2">python</a>
    </li>
    
    <li class="article-tag-list-item">
        <a class="color5">网站推荐</a>
    </li>
    
    <li class="article-tag-list-item">
        <a class="color5">考研经验</a>
    </li>
    
    <div class="clearfix"></div>
</div>

    
    <nav id="title-list-nav">
        
        <a id="top" class="python教程 "
           href="/2020/04/03/python%E9%9D%A2%E8%AF%95%E9%A2%98/"
           data-tag="python"
           data-author="" >
            <span class="post-title" title="python面试题(不定期更新)">python面试题(不定期更新)</span>
            <span class="post-date" title="2020-04-03 21:14:43">2020/04/03</span>
        </a>
        
        <a id="top" class="考研经验 "
           href="/2020/02/20/%E8%80%83%E7%A0%94%E5%88%9D%E8%AF%95%E7%BB%8F%E9%AA%8C/"
           data-tag="考研经验"
           data-author="" >
            <span class="post-title" title="考研初试经验">考研初试经验</span>
            <span class="post-date" title="2020-02-20 19:33:48">2020/02/20</span>
        </a>
        
        <a  class="机器学习实战 "
           href="/2020/04/19/%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="逻辑回归代码实现">逻辑回归代码实现</span>
            <span class="post-date" title="2020-04-19 21:09:25">2020/04/19</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/04/14/%E9%A9%AC%E5%B0%94%E5%8F%AF%E5%A4%AB%E9%93%BE/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="马尔可夫链">马尔可夫链</span>
            <span class="post-date" title="2020-04-14 19:09:29">2020/04/14</span>
        </a>
        
        <a  class="机器学习实战 "
           href="/2020/04/14/%E5%86%B3%E7%AD%96%E6%A0%91%E5%AE%9E%E6%88%98%E9%9A%90%E5%BD%A2%E7%9C%BC%E9%95%9C%E5%88%86%E7%B1%BB/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="决策树实战隐形眼镜分类">决策树实战隐形眼镜分类</span>
            <span class="post-date" title="2020-04-14 10:49:40">2020/04/14</span>
        </a>
        
        <a  class="机器学习实战 "
           href="/2020/04/12/KNN%E5%AE%9E%E6%88%98%E4%B9%8B%E6%B5%B7%E4%BC%A6%E7%BA%A6%E4%BC%9A/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="KNN实战之海伦约会">KNN实战之海伦约会</span>
            <span class="post-date" title="2020-04-12 08:22:12">2020/04/12</span>
        </a>
        
        <a  class="博客搭建 "
           href="/2020/04/08/hexo-%E4%B8%BB%E9%A2%98%E6%B7%BB%E5%8A%A0%E8%AF%84%E8%AE%BA/"
           data-tag="博客搭建"
           data-author="" >
            <span class="post-title" title="hexo 主题添加评论">hexo 主题添加评论</span>
            <span class="post-date" title="2020-04-08 21:43:26">2020/04/08</span>
        </a>
        
        <a  class="项目实战 "
           href="/2020/03/30/%E6%98%8E%E5%A4%A9%E4%BC%9A%E4%B8%8B%E9%9B%A8%E5%90%97%EF%BC%9F/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="明天会下雨吗？">明天会下雨吗？</span>
            <span class="post-date" title="2020-03-30 11:25:31">2020/03/30</span>
        </a>
        
        <a  class="项目实战 "
           href="/2020/03/23/%E5%86%B3%E7%AD%96%E6%A0%91%E5%AE%9E%E7%8E%B0Titanic-%E9%87%8D%E8%A6%81/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="决策树实现Titanic(重要)">决策树实现Titanic(重要)</span>
            <span class="post-date" title="2020-03-23 17:09:05">2020/03/23</span>
        </a>
        
        <a  class="项目实战 "
           href="/2020/03/21/Titanic-%E9%A1%B9%E7%9B%AE%E8%AF%A6%E8%A7%A3/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="Titanic 项目详解">Titanic 项目详解</span>
            <span class="post-date" title="2020-03-21 14:07:20">2020/03/21</span>
        </a>
        
        <a  class="项目实战 "
           href="/2020/03/19/kaggle%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="kaggle项目实战，Titanic analysis">kaggle项目实战，Titanic analysis</span>
            <span class="post-date" title="2020-03-19 10:08:13">2020/03/19</span>
        </a>
        
        <a  class=""
           href="/2020/03/17/Pytorch-%E6%90%AD%E5%BB%BA%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C/"
           data-tag=""
           data-author="" >
            <span class="post-title" title="Pytorch 搭建神经网络">Pytorch 搭建神经网络</span>
            <span class="post-date" title="2020-03-17 14:56:16">2020/03/17</span>
        </a>
        
        <a  class=""
           href="/2020/03/16/CNN%E5%8E%9F%E7%90%86/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="CNN">CNN</span>
            <span class="post-date" title="2020-03-16 09:11:00">2020/03/16</span>
        </a>
        
        <a  class=""
           href="/2020/03/14/%E9%9A%8F%E6%9C%BA%E6%A3%AE%E6%9E%97%E5%92%8Ck%E5%9D%87%E5%80%BC/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="random forest and k means">random forest and k means</span>
            <span class="post-date" title="2020-03-14 16:29:22">2020/03/14</span>
        </a>
        
        <a  class=""
           href="/2020/03/13/%E6%94%AF%E6%8C%81%E5%90%91%E9%87%8F%E6%9C%BA%E7%AE%97%E6%B3%95/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="支持向量机">支持向量机</span>
            <span class="post-date" title="2020-03-13 20:53:20">2020/03/13</span>
        </a>
        
        <a  class=""
           href="/2020/03/11/Matplotlab/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="Matplotlab">Matplotlab</span>
            <span class="post-date" title="2020-03-11 10:13:20">2020/03/11</span>
        </a>
        
        <a  class=""
           href="/2020/03/10/pandas/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="pandas">pandas</span>
            <span class="post-date" title="2020-03-10 09:20:27">2020/03/10</span>
        </a>
        
        <a  class=""
           href="/2020/03/09/logical-regression/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="logical regression">logical regression</span>
            <span class="post-date" title="2020-03-09 20:30:33">2020/03/09</span>
        </a>
        
        <a  class="学习网站推荐 "
           href="/2020/03/08/%E5%AD%A6%E4%B9%A0%E7%BD%91%E7%AB%99%E6%88%96%E5%B7%A5%E5%85%B7%E6%8E%A8%E8%8D%90/"
           data-tag="网站推荐"
           data-author="" >
            <span class="post-title" title="学习网站或工具推荐">学习网站或工具推荐</span>
            <span class="post-date" title="2020-03-08 20:44:55">2020/03/08</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/03/08/%E8%B4%9D%E5%8F%B6%E6%96%AF%E5%88%86%E6%9E%90/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="贝叶斯分析">贝叶斯分析</span>
            <span class="post-date" title="2020-03-08 20:11:15">2020/03/08</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/03/08/numpy/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="numpy的使用">numpy的使用</span>
            <span class="post-date" title="2020-03-08 19:15:54">2020/03/08</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/03/07/%E5%86%B3%E7%AD%96%E6%A0%91/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="决策树">决策树</span>
            <span class="post-date" title="2020-03-07 19:27:38">2020/03/07</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/03/06/K-%E8%BF%91%E9%82%BB%E7%AE%97%E6%B3%95/"
           data-tag="算法"
           data-author="" >
            <span class="post-title" title="K-近邻算法">K-近邻算法</span>
            <span class="post-date" title="2020-03-06 20:18:19">2020/03/06</span>
        </a>
        
        <a  class="算法 "
           href="/2020/03/05/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/"
           data-tag="算法"
           data-author="" >
            <span class="post-title" title="排序算法">排序算法</span>
            <span class="post-date" title="2020-03-05 19:41:32">2020/03/05</span>
        </a>
        
        <a  class="算法 "
           href="/2020/03/04/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6/"
           data-tag="算法"
           data-author="" >
            <span class="post-title" title="数据结构与时间复杂度">数据结构与时间复杂度</span>
            <span class="post-date" title="2020-03-04 21:00:32">2020/03/04</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/03/04/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E6%95%B0%E5%AD%A6%E5%9F%BA%E7%A1%80/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="机器学习数学基础">机器学习数学基础</span>
            <span class="post-date" title="2020-03-04 16:48:34">2020/03/04</span>
        </a>
        
        <a  class="算法 "
           href="/2020/03/03/leetcode%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0/"
           data-tag="算法"
           data-author="" >
            <span class="post-title" title="哈希图 and 移动窗口">哈希图 and 移动窗口</span>
            <span class="post-date" title="2020-03-03 18:49:52">2020/03/03</span>
        </a>
        
        <a  class="机器学习 "
           href="/2020/03/01/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E5%9F%BA%E6%9C%AC%E6%9C%AF%E8%AF%AD/"
           data-tag="机器学习"
           data-author="" >
            <span class="post-title" title="1 零基础学机器学习">1 零基础学机器学习</span>
            <span class="post-date" title="2020-03-01 20:23:40">2020/03/01</span>
        </a>
        
        <a  class="博客搭建 "
           href="/2020/02/20/Windows%E7%B3%BB%E7%BB%9F%E4%B8%8B%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2/"
           data-tag="博客搭建"
           data-author="" >
            <span class="post-title" title="Windows系统下用hexo搭建个人博客">Windows系统下用hexo搭建个人博客</span>
            <span class="post-date" title="2020-02-20 13:15:25">2020/02/20</span>
        </a>
        
    </nav>
</div>
    </div>
    <div class="hide-list">
        <div class="semicircle">
            <div class="brackets first"><</div>
            <div class="brackets">&gt;</div>
        </div>
    </div>
</aside>
<div class="post">
    <div class="pjax">
        <article id="post-python面试题" class="article article-type-post" itemscope itemprop="blogPost">
    
        <h1 class="article-title">python面试题(不定期更新)</h1>
    
    <div class="article-meta">
        
        <span class="top"><a>置顶</a></span>
        
        
        
        <span class="book">
            
                <a  data-rel="python教程">python教程</a>
            
        </span>
        
        
        <span class="tag">
            
            <a class="color2">python</a>
            
        </span>
        
    </div>
    <div class="article-meta">
        
        创建时间:<time class="date" title='更新时间: 2020-04-14 19:22:50'>2020-04-03 21:14</time>
        
    </div>
    <div class="article-meta">
        
        <span>字数:3.3k</span>
        
        
        <span id="busuanzi_container_page_pv">
            阅读:<span id="busuanzi_value_page_pv">
                <span class="count-comment">
                    <span class="spinner">
                      <div class="cube1"></div>
                      <div class="cube2"></div>
                    </span>
                </span>
            </span>
        </span>
        
        
        <span class="top-comment" title="跳转至评论区">
            <a href="#comments">
                评论:<span class="count-comment">
                    <span class="spinner">
                      <div class="cube1"></div>
                      <div class="cube2"></div>
                    </span>
                </span>
            </a>
        </span>
        
    </div>
    
    <div class="toc-ref">
    
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#参考文档地址"><span class="toc-text"> 参考文档地址</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#函数的参数传递机制"><span class="toc-text"> 函数的参数传递机制</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#类方法中cls和self的区别"><span class="toc-text"> 类方法中cls和self的区别</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#类变量和实例变量"><span class="toc-text"> 类变量和实例变量</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#python-的自省"><span class="toc-text"> python 的自省</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#字典推导式"><span class="toc-text"> 字典推导式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#单下划线和双下划线"><span class="toc-text"> 单下划线和双下划线</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#字符串格式化format"><span class="toc-text"> 字符串格式化format</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#迭代器和生成器"><span class="toc-text"> 迭代器和生成器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#args-and-kwargs"><span class="toc-text"> *args and **kwargs</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#修饰器"><span class="toc-text"> 修饰器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#鸭子类型"><span class="toc-text"> 鸭子类型</span></a></li></ol>
    
<style>
    .left-col .switch-btn,
    .left-col .switch-area {
        display: none;
    }
    .toc-level-3 i,
    .toc-level-3 ol {
        display: none !important;
    }
</style>
</div>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p></p>
<h1 id="参考文档地址"><a class="markdownIt-Anchor" href="#参考文档地址"></a> 参考文档地址</h1>
<p>详细请看<a href="https://github.com/Miki123-gif/interview_python" target="_blank" rel="noopener">GitHub</a></p>
<h1 id="函数的参数传递机制"><a class="markdownIt-Anchor" href="#函数的参数传递机制"></a> 函数的参数传递机制</h1>
<p>看两个例子:</p>
<pre class="highlight"><code class="">a = 1
def fun(a):
    a = 2
fun(a)
print a  # 1
</code></pre>
<pre class="highlight"><code class="">a = []
def fun(a):
    a.append(1)
fun(a)
print a  # [1]
</code></pre>
<p>通过<code>id</code>来看引用<code>a</code>的内存地址可以比较理解：</p>
<pre class="highlight"><code class="">a = 1
def fun(a):
    print &quot;func_in&quot;,id(a)   # func_in 41322472
    a = 2
    print &quot;re-point&quot;,id(a), id(2)   # re-point 41322448 41322448
print &quot;func_out&quot;,id(a), id(1)  # func_out 41322472 41322472
fun(a)
print a  # 1
</code></pre>
<p>而第2个例子a引用保存的内存值就不会发生变化：</p>
<pre class="highlight"><code class="">a = []
def fun(a):
    print &quot;func_in&quot;,id(a)  # func_in 53629256
    a.append(1)
print &quot;func_out&quot;,id(a)     # func_out 53629256
fun(a)
print a  # [1]
</code></pre>
<ol>
<li>函数内外都用的同一个标签a，先给1赋一个内存地址，让a标签指向这个内存</li>
<li>传入到函数中的a中函数的a标签指向了1，当重新赋值时，就会指向2的地址</li>
<li>函数内部调用完后，地址就会自动释放，a又指向了1的地址</li>
</ol>
<p><strong>重点：</strong></p>
<p><strong>为什么1中传入数字到函数中，函数外并没改变a标签的值，而当传入的是一个列表，并向列表中添加数值时，函数外的a列表却发生变化？</strong></p>
<p>因为传入的对象不同，python中的对象有：</p>
<ol>
<li>可修改对象：包括字典dict，列表list，集合set</li>
<li>不可修改对象：数字numbers，元组tuple，字符串string</li>
</ol>
<p><strong>当我们给函数中传入不可修改对象时</strong>，形参a会自动复制一个新的变量，和外面的a一点关系都没了</p>
<pre class="highlight"><code class="">a = 1
def fun(a):
    # 形参a会自动复制一个新的变量，和外面的a一点关系都没了
    a = 2
    # 调用完后自动释放，所以外面引用不到里面的
fun(a)
print a  # 1
</code></pre>
<p><strong>当我们传入可修改的对象时</strong>，python就会有个指针，一直指向这个可修改的对象，在函数里面，形参依旧可以修改该对象的值</p>
<p><strong>此问题的关键就是看传入函数的是可修改的对象还是不可修改的对象</strong></p>
<h1 id="类方法中cls和self的区别"><a class="markdownIt-Anchor" href="#类方法中cls和self的区别"></a> 类方法中cls和self的区别</h1>
<p><a href="https://blog.csdn.net/daijiguo/article/details/78499422" target="_blank" rel="noopener">参考自CSDN</a></p>
<ul>
<li><strong>cls是类本身，self是实例本身</strong></li>
</ul>
<p>如果用了staticmethod，那么就可以无视这个self，将这个方法当成一个普通的函数使用。</p>
<pre class="highlight"><code class="">&gt;&gt;&gt; class A(object):
        def foo1(self):
            print &quot;Hello&quot;,self
        @staticmethod
        def foo2():
            print &quot;hello&quot;
        @classmethod
        def foo3(cls):
            print &quot;hello&quot;,cls


&gt;&gt;&gt; a = A()

&gt;&gt;&gt; a.foo1()          #最常见的调用方式，但与下面的方式相同
Hello &lt;__main__.A object at 0x9f6abec&gt;

&gt;&gt;&gt; A.foo1(a)         #这里传入实例a，相当于普通方法的self
Hello &lt;__main__.A object at 0x9f6abec&gt;

&gt;&gt;&gt; A.foo2()          #这里，由于静态方法没有参数，故可以不传东西
hello

&gt;&gt;&gt; A.foo3()          #这里，由于是类方法，因此，它的第一个参数为类本身。
hello &lt;class '__main__.A'&gt;

&gt;&gt;&gt; A                 #可以看到，直接输入A，与上面那种调用返回同样的信息。
&lt;class '__main__.A'&gt;
</code></pre>
<h1 id="类变量和实例变量"><a class="markdownIt-Anchor" href="#类变量和实例变量"></a> 类变量和实例变量</h1>
<p><strong>先说明下什么是类变量，什么是实例变量：</strong></p>
<p>注意类开头字母要大写，普通函数开头要小写，这是约定</p>
<pre class="highlight"><code class="">class Test：
    number = 0
    def __init__(self):
        self.number = 0
</code></pre>
<ul>
<li>number就是类变量，self.number就是实例变量</li>
</ul>
<p><strong>问题1：</strong><br />
两者是如何使用的？</p>
<p>下例中，num_of_instance 就是类变量，用于跟踪存在着多少个Test 的实例。</p>
<pre class="highlight"><code class="">class Test(object):  
    num_of_instance = 0  
    def __init__(self, name):  
        self.name = name  
        Test.num_of_instance += 1  
  
if __name__ == '__main__':  
    print Test.num_of_instance   # 0
    t1 = Test('jack')  
    print Test.num_of_instance   # 1
    t2 = Test('lucy')  
    print t1.name , t1.num_of_instance  # jack 2
    print t2.name , t2.num_of_instance  # lucy 2
</code></pre>
<p><strong>问题2：</strong></p>
<pre class="highlight"><code class="">class Person:
    name=&quot;aaa&quot;

p1=Person()
p2=Person()
p1.name=&quot;bbb&quot;
print p1.name  # bbb
print p2.name  # aaa
print Person.name  # aaa
</code></pre>
<p><strong>一开始p1.name指向类变量中的name，当我们对实例p1.name修改时，p1.name就不再指向name类变量了，而变成了实例变量，所以我们再次输出类变量name的值时，发现并没有改变</strong></p>
<pre class="highlight"><code class="">class Test:
    a = []
# 实例化
p1 = Test()
p2 = Test()
p1.a.append(1)
print(Test.a)
p2.a.append(2)
print(Test.a)
print(p1.a)

[1]
[1, 2]
[1, 2]
</code></pre>
<p><strong>重点在于看传入的是可修改的还是不可修改的，如果是不可修改的类对象，那就不会改变类变量的值，如果是可修改类对象，则会有个指针指向列表等对象</strong></p>
<h1 id="python-的自省"><a class="markdownIt-Anchor" href="#python-的自省"></a> python 的自省</h1>
<p>就是python能够获得对象的属性，如dir可以查看函数的方法，isinstance可以查看两个属性是否一样</p>
<pre class="highlight"><code class="">a = list('123') # ['1', '2', '3']
b = {1:2,3:4}
isinstance(a, dict) # False
dir(isinstance) # ['__call__', '__class__', '__delattr__
</code></pre>
<h1 id="字典推导式"><a class="markdownIt-Anchor" href="#字典推导式"></a> 字典推导式</h1>
<p>语法：</p>
<pre class="highlight"><code class="">d = {key: value for (key, value) in iterable}
</code></pre>
<p>例如：</p>
<pre class="highlight"><code class="">dict1 = {1:2,3:4,'a':'b'}
print(dict1.items()) # dict_items([(1, 2), (3, 4), ('a', 'b')])

a = {key: value for key, value in dict1.items() if isinstance(key,str)}
print(a) # {'a': 'b'}
</code></pre>
<h1 id="单下划线和双下划线"><a class="markdownIt-Anchor" href="#单下划线和双下划线"></a> 单下划线和双下划线</h1>
<ul>
<li>双下划线__init__(self)指的是魔法方法，类中会自己调用的一种方法，如果类中有__add__()方法，则说明，当我们使用+号时，就会调用这个类中的魔法方法</li>
<li>self.__superprivate私有变量，外界不能直接访问该属性名，是python的匿名机制，不过换一种方式就可以访问，通过对象名._类名__xxx这样的方式可以访问.</li>
<li>self._semiprivate，假如我们完成一个模块，当别人导入这个模块时，是无法查看这个属性的，因为根本就没法导入，不能用from module import * 导入</li>
</ul>
<pre class="highlight"><code class="">&gt;&gt;&gt; class MyClass():
...     def __init__(self):
...             self.__superprivate = &quot;Hello&quot;
...             self._semiprivate = &quot;, world!&quot;
...
&gt;&gt;&gt; mc = MyClass()
&gt;&gt;&gt; print mc.__superprivate
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
AttributeError: myClass instance has no attribute '__superprivate'
&gt;&gt;&gt; print mc._semiprivate
, world!
&gt;&gt;&gt; print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}
</code></pre>
<h1 id="字符串格式化format"><a class="markdownIt-Anchor" href="#字符串格式化format"></a> 字符串格式化format</h1>
<ul>
<li>如果使用%输出想打印一个元组，则会抛出TypeErro错误，所以输出最好直接使用format</li>
</ul>
<pre class="highlight"><code class="">a = (1,2,3)
print(f'{a}')
print('a:%s'%a) # TypeError
</code></pre>
<h1 id="迭代器和生成器"><a class="markdownIt-Anchor" href="#迭代器和生成器"></a> 迭代器和生成器</h1>
<p>参考笔记：<br />
<a href="https://blog.csdn.net/mieleizhi0522/article/details/82142856" target="_blank" rel="noopener">https://blog.csdn.net/mieleizhi0522/article/details/82142856</a></p>
<p>yield相当于函数中的return，yield后面的都不会运行，并且会返回一个值，不同点在于yield配合next，可以实现中断功能</p>
<pre class="highlight"><code class="">def myGener():
    for i in range(10):
        yield i
        print('-'*20)
        print('hello')

g = myGener()      
print(type(g))# &lt;class 'generator'&gt;  
print(next(g))# 0
print('hello')
print(next(g))# hello， 1
print(next(g))# hello， 2
</code></pre>
<ul>
<li>当函数中有yield时，我们就生成了一个生成器对象，就像类一样，要先进行实例化,此时函数并不会全部直接运行，而是先生成一个迭代器，当我们需要调用时，才会进行运行，大大节省了内存</li>
<li>yield相当于一个中断，遇到next会往下运行</li>
</ul>
<pre class="highlight"><code class="">def myGener():
    for i in range(10):
        yield i

myGener()        
print(next(myGener()))
print('hello')
print(next(myGener()))
print(next(myGener()))

# 这里输出全为0，并没有像上面那样，就是因为没有实例化
0
hello
0
0

</code></pre>
<p><strong>当列表推导式的<code>[]</code>变成<code>()</code>，生成的还是列表吗？</strong></p>
<p>此时生成的是生成器，不再是列表了，区别在于列表推导式会一次性将整个列表生成，当数据很大时，会消耗大量的内存，生成器只有当我们需要的时候，才会生成</p>
<p>当我们只需要少量的数据时，这里依旧可以使用next获取<br />
<strong>生成器貌似都能配合for循环和next生成数据</strong></p>
<pre class="highlight"><code class="">g = (x for x in range(10))
for i in range(5):
    print(next(g))
    
# 输出
0
1
2
3
4
</code></pre>
<h1 id="args-and-kwargs"><a class="markdownIt-Anchor" href="#args-and-kwargs"></a> *args and **kwargs</h1>
<ul>
<li>当定义一个函数，不知道要传入多少参数时，使用*<strong>arg</strong></li>
</ul>
<pre class="highlight"><code class="">def test(*name):
    print(type(name))
    print(name)
    
test(1,2,'a')


&lt;class 'tuple'&gt;
(1, 2, 'a')
</code></pre>
<ul>
<li>如果想向函数中传入一些属性，则使用**arg，允许你使用没有事先定义的参数名</li>
</ul>
<pre class="highlight"><code class="">def tes(**name):
    print(type(name))
    print(name)
    
tes(fruit = 'apple',veg = 'cabbage')
</code></pre>
<p>输出：</p>
<pre class="highlight"><code class="">&lt;class 'dict'&gt;
{'fruit': 'apple', 'veg': 'cabbage'}
</code></pre>
<ul>
<li>混合使用</li>
</ul>
<p><strong>参数a会先获得值，剩下的传给arg</strong></p>
<pre class="highlight"><code class="">def test(a,*arg):
    print(a)
    print(arg)

test('a',12,23)
</code></pre>
<p><strong>也可以这样混合使用</strong></p>
<p>*<strong>args和**kwargs可以同时在函数的定义中,但是*args必须在**kwargs前面.</strong></p>
<pre class="highlight"><code class="">def test(a,*arg,**name):
    print(a)
    print(arg)
    print(name)

test('a',12,23,title = 'zhu',d ='c')
# 输出
a
(12, 23)
{'title': 'zhu', 'd': 'c'}
</code></pre>
<h1 id="修饰器"><a class="markdownIt-Anchor" href="#修饰器"></a> 修饰器</h1>
<p>修饰器就是在不改变原来函数的接口上，给函数添加一些新的功能</p>
<p><strong>我们先来理解一个概念，请看下面代码：</strong></p>
<pre class="highlight"><code class="">import time

def calculate():
    star = time.time()
    time.sleep(2)
    end = time.time()
    print(end - star)

another = calculate

another() # 2.0003886222839355
</code></pre>
<blockquote>
<p>我们讲函数名calculate传给了another，然后再调用another函数，一样可以打印</p>
</blockquote>
<p><strong>当我们删掉calculate函数时，another函数还能继续使用</strong></p>
<pre class="highlight"><code class="">import time

def calculate():
    star = time.time()
    time.sleep(2)
    end = time.time()
    print(end - star)

another = calculate

print(id(another)) # 1656403252136

print(id(calculate)) # 1656403252136

del calculate # 删除原先的函数名
try:
    calculate()
except:
    print('func name not exist')

another()


func name not exist
2.0008578300476074
</code></pre>
<p><strong>现在，假设我们要给每一个函数，都额外添加一个计算函数运行时间的功能，使用修饰器来完成这个任务</strong></p>
<ol>
<li>写一个计算时间的修饰器</li>
<li>给每个函数都装饰上这个修饰器</li>
</ol>
<p><strong>假如现在有一个func函数，我们要计算这个函数的运行时间，一般做法如下：</strong></p>
<pre class="highlight"><code class="">import time

def calculate():
    star = time.time()
    func()
    end = time.time()
    print(end - star)

def func():
    print('testing...')
    time.sleep(2)

calculate()
</code></pre>
<p><strong>但如果函数很多，每个都这样写，就太麻烦了</strong></p>
<p>额…利用刚才的知识，我想到一个方法，虽然也比较简单，但是致命的是里面利用了循环，这会大大增加运算的复杂度，而且<strong>函数的调用接口变换了，我们希望再使用func1的时候，就打印时间出来</strong></p>
<pre class="highlight"><code class="">import time

def calculate(*args):
    for each in args:
        star = time.time()
        each()
        end = time.time()
        print(end - star)

def func1():
    print('testing 1 ...')
    time.sleep(2)

def func2():
    print('testing 2 ...')
    time.sleep(2)
    
calculate(func1, func2)

testing 1 ...
2.0000758171081543
testing 2 ...
2.0015196800231934

</code></pre>
<p><strong>开始用修饰器，实现上面功能</strong></p>
<p><strong>初步实现，此时不改变接口</strong></p>
<ol>
<li>将要添加的功能，写成闭包的形式，添加函数func1</li>
<li>重新给func1指向内部的inner函数，看下面代码</li>
</ol>
<pre class="highlight"><code class="">import time

def calculate(func): # 这里传入要计算时间的方程
    def inner(): # 写成闭包形式
        star = time.time()
        func() # func相当于是个标签，表示传入的函数
        end = time.time()
        print(end - star)
    return inner # 返回inner函数标签，因为外面想直接使用inner是不行的
    
def func1():
    print('testing 1 ...')
    time.sleep(2)

def func2():
    print('testing 2 ...')
    time.sleep(2)
    
print(id(func1))     # 1656403252856
func1 = calculate(func1) # 相当于func1 = inner，修改下标签的指向
# 这样外部函数func1，既可以使用自己原来的功能，又计算了时间
print(id(func1)) # 1656403254152
func1()

testing 1 ...
2.000030517578125
</code></pre>
<p>如果每次都要执行一次<code>func1 = calculate(func1)</code>，就有些复杂了，python提供了一个语法糖@，<strong>进行下面修改即可</strong></p>
<pre class="highlight"><code class="">import time

# 修饰器，一定要写在要使用该修饰器的函数前面
def calculate(func):
    def inner():
        star = time.time()
        func()
        end = time.time()
        print(end - star)
    return inner

@calculate   # 语法糖，相当于指令func1 = calculate(func1) 
def func1():
    print('testing 1 ...')
    time.sleep(2)
    
@calculate # 相当于指令func2 = calculate(func2)
def func2():
    print('testing 2 ...')
    time.sleep(2)
       
# func1 = calculate(func1)
func1()

testing 1 ...
2.000004768371582

</code></pre>
<h1 id="鸭子类型"><a class="markdownIt-Anchor" href="#鸭子类型"></a> 鸭子类型</h1>
<p>当一只鸟走起来像鸭子，叫起来也像鸭子，我们就认为这只鸟是鸭子</p>
<p>鸭子类型就是，我们不关注对象的类型，只关心对象的方法</p>
<p><strong>通过鸭子类型的思想进行设计：当我们想自定义个类方法，我们想让他像容器一样，可以存放东西，我们就必须定义一个方法，让这个类长得想一个容器，可以在类中定义__iter__魔法方法，只要有这个方法，他就叫起来像鸭子了</strong></p>
<p><strong>list的extend方法，不仅可以传入列表，而且可以传入字符串和元组等任何可以迭代的容器，因为容器中都有一个共同的属性，iterable，extend函数就是会调用这些容器中共同的方法</strong></p>
<pre class="highlight"><code class="">a = [1,2,3]
b = [4,5,6]
c = (1,2)
d = '123'
a.extend(b)
print(a)
a.extend(c)
print(a)
a.extend(d)
print(a)

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2]
[1, 2, 3, 4, 5, 6, 1, 2, '1', '2', '3']

</code></pre>
<p><strong>再来看一个例子：</strong><br />
<strong>这里有三个需要注意的地方</strong></p>
<p><strong>1. 类中想调用自己类中的方法，则使用self.func()</strong></p>
<p><strong>2. 想直接调用类中的方法，则需要实例化再调用，直接Cat().say(),其中Cat()加括号就是实例化</strong></p>
<p><strong>3. python中标签可以指向任何对象，不管是类名还是变量名</strong></p>
<p>例子中类都有say方法，不管他是什么类对象，我只需要调用里面共有的say方法</p>
<pre class="highlight"><code class="">class Dog:
    def say(self):
        print('喵~')
    # print('汪汪')
    # 如果我们想让狗变得像猫，可以定义它的叫声像猫，走路像猫
        
    
    def run(self):
        self.say()
        print('i am running')

class Cat:
    def say(self):
        print('喵~')
    
animal_list = [Dog, Cat]

for animal in animal_list:
    animal().say()
</code></pre>
<p><strong>总结：鸭子类型是编写类方法的核心思想，我们想让类方法具有容器功能，只需要让它具备容器的特征，需要让这个容器可迭代，则只需要让它具备可迭代的功能即可</strong></p>

      
       
    </div>
</article>



<div class="article_copyright">
    <p><span class="copy-title">文章标题:</span>python面试题(不定期更新)</p>
    <p><span class="copy-title">文章字数:</span><span class="post-count">3.3k</span></p>
    <p><span class="copy-title">本文作者:</span><a  title="Miki Zhu">Miki Zhu</a></p>
    <p><span class="copy-title">发布时间:</span>2020-04-03, 21:14:43</p>
    <p><span class="copy-title">最后更新:</span>2020-04-14, 19:22:50</p>
    <span class="copy-title">原始链接:</span><a class="post-url" href="/2020/04/03/python%E9%9D%A2%E8%AF%95%E9%A2%98/" title="python面试题(不定期更新)">http://mikiblog.online/2020/04/03/python%E9%9D%A2%E8%AF%95%E9%A2%98/</a>
    <p>
        <span class="copy-title">版权声明:</span><i class="fa fa-creative-commons"></i> <a rel="license noopener" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
    </p>
</div>



    <div id="vcomment" class="comment"></div> 
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<script src="https://cdnjs.loli.net/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    var notify = 'false' == true ? true : false;
    var verify = 'false' == true ? true : false;
    new Valine({
        av: AV,
        el: '#vcomment',
        notify: notify,
        app_id: "3uM9nFQKJdCUOHqwT3LHL5Mt-gzGzoHsz",
        app_key: "3v4CdFJJjh97olrmyHxtdDlt",
        placeholder: "请输入",
        avatar:"mm",
    });
</script>



    





  <section id="comments" class="vcomment">
  </section>

    </div>
    <div class="copyright">
        <p class="footer-entry">©2016-2019 MikiZhu 赣ICP备20004640号</p>
<p class="footer-entry">Built with <a href="https://hexo.io/" target="_blank">Hexo</a> and <a href="https://github.com/yelog/hexo-theme-3-hexo" target="_blank">3-hexo</a> theme</p>

    </div>
    <div class="full-toc">
        <button class="full"><span class="min "></span></button>
<button class="post-toc-menu"><span class="post-toc-menu-icons"></span></button>
<div class="post-toc"><span class="post-toc-title">目录</span>
    <div class="post-toc-content">

    </div>
</div>
<a class="" id="rocket" ></a>

    </div>
</div>
<div class="acParent"></div>

</body>
<script src="/js/jquery.pjax.js?v=1.0.1" ></script>

<script src="/js/script.js?v=1.0.1" ></script>
<script>
    var img_resize = 'default';
    /*作者、标签的自动补全*/
    $(function () {
        $('.search').AutoComplete({
            'data': ['#机器学习','#算法','#博客搭建','#python','#网站推荐','#考研经验',],
            'itemHeight': 20,
            'width': 418
        }).AutoComplete('show');
    })
    function initArticle() {
        /*渲染对应的表格样式*/
        
            $(".post .pjax table").addClass("green_title");
        

        /*渲染打赏样式*/
        

        /*高亮代码块行号*/
        

        /*访问数量*/
        
        $.getScript("//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js");
        

        /*代码高亮，行号对齐*/
        $('.pre-numbering').css('line-height',$('.has-numbering').css('line-height'));

        
        
    }

    /*打赏页面隐藏与展示*/
    

</script>

<!--加入行号的高亮代码块样式-->

<!--自定义样式设置-->
<style>
    
    
    .nav {
        width: 542px;
    }
    .nav.fullscreen {
        margin-left: -542px;
    }
    .nav-left {
        width: 120px;
    }
    
    
    @media screen and (max-width: 1468px) {
        .nav {
            width: 492px;
        }
        .nav.fullscreen {
            margin-left: -492px;
        }
        .nav-left {
            width: 100px;
        }
    }
    
    
    @media screen and (max-width: 1024px) {
        .nav {
            width: 492px;
            margin-left: -492px
        }
        .nav.fullscreen {
            margin-left: 0;
        }
        .nav .hide-list.fullscreen {
            left: 492px
        }
    }
    
    @media screen and (max-width: 426px) {
        .nav {
            width: 100%;
        }
        .nav-left {
            width: 100%;
        }
    }
    
    
    .nav-right .title-list nav a .post-title, .nav-right .title-list #local-search-result a .post-title {
        color: #383636;
    }
    
    
    .nav-right .title-list nav a .post-date, .nav-right .title-list #local-search-result a .post-date {
        color: #5e5e5f;
    }
    
    
    .nav-right nav a.hover, #local-search-result a.hover{
        background-color: #e2e0e0;
    }
    
    

    /*列表样式*/
    
    .post .pjax article .article-entry>ol, .post .pjax article .article-entry>ul, .post .pjax article>ol, .post .pjax article>ul{
        border: #e2dede solid 1px;
        border-radius: 10px;
        padding: 10px 32px 10px 56px;
    }
    .post .pjax article .article-entry li>ol, .post .pjax article .article-entry li>ul,.post .pjax article li>ol, .post .pjax article li>ul{
        padding-top: 5px;
        padding-bottom: 5px;
    }
    .post .pjax article .article-entry>ol>li, .post .pjax article .article-entry>ul>li,.post .pjax article>ol>li, .post .pjax article>ul>li{
        margin-bottom: auto;
        margin-left: auto;
    }
    .post .pjax article .article-entry li>ol>li, .post .pjax article .article-entry li>ul>li,.post .pjax article li>ol>li, .post .pjax article li>ul>li{
        margin-bottom: auto;
        margin-left: auto;
    }
    

    /* 背景图样式 */
    
    


    /*引用块样式*/
    

    /*文章列表背景图*/
    
    .nav-right:before {
        content: ' ';
        display: block;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0.4;
        background: url("http://q8idlsxje.bkt.clouddn.com/%E6%B5%B7%E6%BB%A9.jpg");
        background-repeat: no-repeat;
        background-position: 50% 0;
        -ms-background-size: cover;
        -o-background-size: cover;
        -moz-background-size: cover;
        -webkit-background-size: cover;
        background-size: cover;
    }
    

    
</style>







  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  <script>
    var GUEST_INFO = ['nick','mail','link'];
    var guest_info = 'nick,mail,link'.split(',').filter(function(item){
        return GUEST_INFO.indexOf(item) > -1
    });
    var notify = 'false' == true;
    var verify = 'false' == true;
    new Valine({
      el: '.vcomment',
      notify: notify,
      verify: verify,
      appId: "3uM9nFQKJdCUOHqwT3LHL5Mt-gzGzoHsz",
      appKey: "3v4CdFJJjh97olrmyHxtdDlt",
      placeholder: "请输入",
      pageSize: '10',
      avatar: 'mm',
      lang: 'zh-cn',
      visitor: 'true'
    });
  </script>

</html>
